import { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import dayjs from 'dayjs'
import { View, Image,Text  } from '@tarojs/components'
import { staticUrl } from '@/utils'
import CarInfo from '@/components/CarInfo/CarView3'
import GoodList from '@/components/GoodsView/GoodList'
import MoreView from '@/components/GoodsView/MoreView'
import StateList from '@/components/StateList'
import Iconfont from '@/components/Iconfont'
import CountDown from '@/components/CountDown'
import { AtActionSheet, AtActionSheetItem, AtTimeline } from 'taro-ui'
import { getOrderDetails, cancelOrder, cancelBooking, ensurePlatformPay } from '@/api/order'
import './index.scss'

const bar1 = staticUrl('/img/order/bar1.png')
const bar2 = staticUrl('/img/order/bar2.png')
const bar3 = staticUrl('/img/order/bar3.png')
const payIcon = staticUrl('/img/order/pay-icon.png')
const server1Icon = staticUrl('/img/order/server-icon.png')
const server2Icon = staticUrl('/img/order/server2-icon.png')
const doneIcon = staticUrl('/img/order/done-icon.png')
const closeIcon = staticUrl('/img/order/close-icon.png')

interface State {
  details: any
  down: boolean
  serverTime: any
  isOpenedDialog: boolean,
  confirmVisable: boolean,
}

export default class Index extends Component {
  $instance = getCurrentInstance();

  constructor (props) {
    super(props)
    this.state = {
      details: {},
      down: false,
      serverTime: null,
      isOpenedDialog: false,
      confirmVisable: true
    }
  }
  state: State
  UNSAFE_componentWillMount() {
    this.checkNavigate()
  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }

  // 检查导航
  checkNavigate() {
    const { orderNumber, order } = this.$instance.router.params
    console.log(this.$instance.router)
    // 去预约页面增加一个订单详情的路由处理
    if (order) {
      Taro.navigateTo({
        url: `/pages/order/booking/index?orderNumber=${orderNumber}&redirect=orderDetails&order=${order}`
      })
    }
  }
  // isCouldViewWarranty = 1 质保详情  clientSource = 11  // http://10.2.0.30:30001/project/6/interface/api/8097
  // 获取订单详情
  initPage() {
    getOrderDetails({
      orderNumber: this.$instance.router.params.orderNumber
    }).then(res => {
      const data = res.data.data
      const serverTime = new Date(res.header.Date).getTime()
      this.setState({
        details: data,
        serverTime
      })
    })
  }
  componentDidShow() {
    this.initPage()
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }
  changeGoodsStatus(e) {
    this.setState({
      down: e
    })
  }
  // 去支付
  toPay() {
    Taro.navigateTo({
      url: '/pages/order/pay/index?orderNumber=' + this.$instance.router.params.orderNumber
    })
  }
  // 预约时间
  bookingOrder(details, mode?) {
    let goods = []
    if (details.items) {
      goods = details.items.goods.map(v => {
        const { goodsId, goodsSkuId, number, type } = v
        return {
          goodsId,
          goodsSkuId,
          number,
          type
        }
      })
    }
    if (mode === 'edit') {
      Taro.navigateTo({ url: `/pages/order/booking/index?orderNumber=${details.orderNumber}&order=${JSON.stringify(goods)}&applyTime=${details.apply.time}` })
    } else {
      Taro.navigateTo({ url: `/pages/order/booking/index?orderNumber=${details.orderNumber}&order=${JSON.stringify(goods)}` })
    }
  }
  // 打电话
  makePhoneCall(phoneNumber) {
    Taro.makePhoneCall({ phoneNumber })
  }

  // 打电话弹框
  showCallPhoneDialog() {
    this.setState({
      isOpenedDialog: true
    })
  }
  closeCallPhoneDialog() {
    this.setState({
      isOpenedDialog: false
    })
  }
  // 申请售后
  applySale(details) {
    this.showCallPhoneDialog()
  }

  // 申请退款
  applyRefund(details) {
    const { action, orderNumber, jihuasuanId, type } = details
    if (type == 1 && jihuasuanId) { // 集划算年卡单独前往退款
      Taro.navigateTo({
        url: '/pages/order/cheapApply/index?orderNumber=' + orderNumber
      })
      return
    }
    if (+action.isCouldShowDialog === 1) {
      // 弹窗
      this.showCallPhoneDialog()
      return
    }
    Taro.navigateTo({
      url: '/pages/order/apply/index?orderNumber=' + orderNumber
    })



  }

  // 查看退款
  viewRefund(details) {
    const { action, orderNumber, refundInfo } = details
    if (+action.isCouldShowDialog === 1) {
      // 弹窗
      this.showCallPhoneDialog()
      return
    }
    Taro.navigateTo({
      url: '/pages/order/refund/index?refundApplyNumber=' + refundInfo.refundApplyNumber + '&orderNumber=' + orderNumber
    })
  }

  // 取消订单
  cancelOrder(details) {
    const { action, orderNumber } = details
    if (+action.isCouldShowDialog === 1) {
      // 弹窗
      this.showCallPhoneDialog()
      return
    }
    Taro.showModal({
      title: '取消订单',
      content: '确定取消订单吗？',
      success: async (res) => {
        try {
          if (res.confirm) {
            await cancelOrder({ orderNumber })
            this.initPage()
            Taro.showToast({
              icon: 'none',
              title: '取消订单成功'
            })
          }
        } catch (e) {
          Taro.showToast({
            icon: 'none',
            title: '接口异常'
          })
        }
      }
    })
  }
  // 取消预约
  cancelApply(orderNumber) {
    Taro.showModal({
      title: '取消预约',
      content: '确定取消预约吗？',
      success: async (res) => {
        try {
          if (res.confirm) {
            await cancelBooking({ orderNumber })
            this.initPage()
            Taro.showToast({
              icon: 'none',
              title: '取消预约成功'
            })
          }
        } catch (e) {
          Taro.showToast({
            icon: 'none',
            title: '接口异常'
          })
        }
      }
    })
  }

  // 质保详情
  viewWarranty(details) {
    let query = {
      orderNumber: details.orderNumber,
      mode: 2
    }
    Taro.navigateTo({ url: `/pages/webview/index/index?path=/quality/create&query=${JSON.stringify(query)}` })
  }

  // 评价
  toEvaluate(details) {
    const { orderNumber } = details
    Taro.navigateTo({ url: `/pages/evaluate/index/index?orderNumber=${orderNumber}` })
  }

  seekTransport(details) {
    const { orderFudeng } = details
    let data = {
      expressNumber: orderFudeng.expressNumber,
      consigneeMobile: orderFudeng.consigneeMobile,
      consigneeAddress: orderFudeng.consigneeAddress,
      expectDateLabel: orderFudeng.expectDateLabel
    }
    Taro.navigateTo({ url: `/pages/order/logistics/index?params=${JSON.stringify(data)}` })
  }


  // 信息确认无误
  handleConfirmPay(status) { // status 1 授权  2拒绝
    let { details } = this.state
    ensurePlatformPay({
      authId: +details.isAuthorizing,
      status
    }).then(res => {
      this.setState({
        confirmVisable: false
      }, () => {
        Taro.showToast({
          icon: 'none',
          title: '操作成功！'
        })
        this.initPage()
      })

    })
  }

  render() {
    const { reloadReport, details, down, serverTime, isOpenedDialog, authId, confirmVisable } = this.state
    let car = {}
    let cartList: any = null
    const detailsLoaded = Object.keys(details).length > 0 ? true : false
    const priceMsg: any = {
      total: 0,
      coupon: 0,
      redPacket: 0,
      superRedPacket: 0,
      recharge: 0,
      discountPrice: 0,
      baobeiRedPacketPrice: 0,
      platformRedPacketPrice: 0,
    }
    let statusIcon = ''
    let hasAction: boolean = false
    let barImg = ''
    if (detailsLoaded) {
      car = {
        brandLogoUrl: details.car && details.car.brandLog,
        id: details.carId,
        isNewEnergy: details.car && Number(details.car.isNewEnergy),
        carLicense: details.carLicense,
        carModelName: details.carModelLabel
      }

      // 方案单
      if (details.type == 2) {
        cartList = details.items && details.items.sku ? details.items.sku : null
      } else {
        cartList = details.items && (Object.keys(details.items).length && details.items.goods) ? details.items.goods : null
      }
      console.log('cartList: ', cartList);
      if (!down && cartList) {
        if (cartList.length > 3) {
          cartList = cartList.slice(0, 3)
        }
      }
			// 年卡单处理卡券可用不可用
			if(details.type == 1){
				let annualCardItem = details.annualCardItem
				console.log('annualCardItem',annualCardItem)
				let itemList = annualCardItem && details.annualCardItem.itemList || []
				itemList.map((item)=>{
					cartList.map((citem=>{
						if(citem.id == item.id){
							item.showType = annualCardItem.showType
							item.label = annualCardItem.label
							citem.annualCardItem = item
						}
					}))
				})
			}
			console.log()
      if (details.totalPrice) {
        priceMsg.total = details.totalPrice
        const hasPromotion: any = details.promotion && Object.keys(details.promotion).length
        let promotion: any
        if (hasPromotion) {
          promotion = details.promotion
          priceMsg.coupon = promotion.couponPrice
          priceMsg.redPacket = (Number(promotion.redPacketPrice) + Number(promotion.superRedPacketPrice) + Number(promotion.baobeiRedPacketPrice) + Number(promotion.platformRedPacketPrice)).toFixed(2)
          priceMsg.superRedPacket = promotion.superRedPacketPrice
          priceMsg.baobeiRedPacketPrice = promotion.baobeiRedPacketPrice
          priceMsg.platformRedPacketPrice = promotion.platformRedPacketPrice
          priceMsg.recharge = promotion.rechargePrice
          priceMsg.total = Number(priceMsg.total) - Number(priceMsg.coupon) - Number(priceMsg.redPacket) - Number(priceMsg.superRedPacket) - Number(priceMsg.baobeiRedPacketPrice) - Number(priceMsg.platformRedPacketPrice) - Number(priceMsg.recharge)
          priceMsg.total = priceMsg.total.toFixed(2)
          priceMsg.discountPrice = promotion.discountPrice
        }
      }
      hasAction = Object.keys(details.action).every(v => details.action[v] == 0)
      switch (details.businessStatus) {
        case 0: statusIcon = payIcon
          break
        case 1: statusIcon = server1Icon
          break
        case 2: statusIcon = server2Icon
          break
        case 3: statusIcon = doneIcon
          break
        case 4: statusIcon = closeIcon
          break
      }
      if ([0, 1, 2].includes(details.businessStatus)) {
        barImg = bar3
      } else if (details.businessStatus === 3) {
        barImg = bar2
      } else if (details.businessStatus === 4) {
        barImg = bar1
      } else {
        barImg = bar1
      }
    }
    let fudengLog = details && details.fudengLog || []

    console.log('details.type', details)
    return detailsLoaded && (
      <View className='order-details'>
        <AtActionSheet isOpened={isOpenedDialog} onClose={this.closeCallPhoneDialog.bind(this)} cancelText='取消' title='当前订单需联系门店终止方案，给您带来不便敬请谅解'>
          <AtActionSheetItem onClick={this.makePhoneCall.bind(this, details.store.phone)}>
            门店热线：{details.store.phone}
          </AtActionSheetItem>
          <AtActionSheetItem onClick={this.makePhoneCall.bind(this, '4008331300')}>
            集群车宝热线：4008331300
          </AtActionSheetItem>
        </AtActionSheet>
        {
          authId == '' ?
            (
              <View className='bar-wrap'>
                <Image className='bar' src={barImg}></Image>
                <View className='status-row'>
                  <View className='status'>
                    <Image className='shalou' src={statusIcon}></Image>
                    {details.businessStatusLabel}
                  </View>
                  {details.businessStatus === 0 && <View className='time'>支付剩余：<CountDown serverTime={serverTime} time={details.createdAt} /></View>}
                </View>
                {
                  details.businessStatus === 0 && <View className='price'>应付金额：<View className='strong'>￥{(Number(details.needPayPrice) - Number(details.realPayPrice)).toFixed(2)}</View></View>
                }
                {
                  details.businessStatus === 1 && <View className='price'>订单已支付，请预约到店服务</View>
                }
                {
                  details.businessStatus === 2 && <View className='price'>订单服务中，请耐心等候</View>
                }
                {
                  details.businessStatus === 3 && <View className='price'>订单已完成，感谢您的支持</View>
                }
              </View>
            ) : null
        }

        <CarInfo loaded disabled carInfo={car} styleView='3' />
        {
          cartList && <View className='goods-item margin-top20'>
            {
              details.type == 1 && (
                <View className='annual-name'>
                  <View className='goods-name'>{details?.annualCardDetail?.annualCardName}</View>
                  <View className='vailday'>
                    <View className='span'>{details?.annualCardDetail?.validDay}天</View>
                    <View className='tips'>有效期</View>
                  </View>
                </View>
              )
            }
            {
              cartList.map((v, index) => {
                return <View key={v.id} className='li'>
                  {
                    // 方案单
                    details.type == 2 && <GoodList list={v} imgUrl={true} />
                  }
                  {
                    details.type != 2 && <GoodList list={v} isNk={details.type == 1 ? true : false}/>
                  }
                </View>
              })
            }
            {details.type == 2 ? details.items && details.items.sku && details.items.sku.length > 3 && <MoreView handle={this.changeGoodsStatus.bind(this)} />
              : details.items && details.items.goods && details.items.goods.length > 3 && <MoreView handle={this.changeGoodsStatus.bind(this)} />
            }
          </View>
        }

      {
			details.annualCardItem && details.annualCardItem.giftList && details.annualCardItem.giftList.length ? <View className='nk-list-inner' >
							<View className='nk-list-header'>
								<Text>赠品</Text>
								{
									details.annualCardItem.showType !== 0 ? <View>
									<Text className='c1'>{details.annualCardItem.label.split('/')[0]}</Text>
									<Text className='c2'>/{details.annualCardItem.label.split('/')[0]}</Text>
								</View> : null
								}

							</View>
							{
							details.annualCardItem.giftList && details.annualCardItem.giftList.length && details.annualCardItem.giftList.map((list)=>{
								return <View className='nk-list-header'>
								<Text className='c2'>{list.goodsName}</Text>
								{
									details.annualCardItem.showType === 0 ? <View>
									<Text className='c2'>x{list.number}</Text>
								</View> : <View>
									<Text className='c1'>{list.type === 1 ? '￥': ''}{list.remainNum}</Text>
									<Text className='c2'>/{list.type === 1 ? '￥': ''}{list.useNum}</Text>
								</View>
								}

							</View>
							}) || null
						}
						</View> : null
						}
        <View className='margin-top20'>
          <StateList name='支付方式' context={details.payMethodLabel} />
          {/* E+订单是通过团长分销下单，且团长为门店员工；显示销售门店 */}
          {
            details.saleStore && details.saleStore.storeName ? (
              <View>
                <StateList name='销售门店' context={details.saleStore.storeName} />
                {
                  <View className='flex'>
                    <StateList handle={() => {
                      // 使用微信内置地图查看位置
                      const { latitude, longitude, address, storeName } = details.store
                      Taro.openLocation({
                        latitude: Number(latitude),
                        longitude: Number(longitude),
                        scale: 18,
                        name: storeName,
                        address
                      })
                    }} name='门店地址' baseline context={details.saleStore.address} />
                    {
                      details.store.phone && <Iconfont handle={() => {
                        // 使用微信内置拨打电话
                        const { phone } = details.store
                        Taro.makePhoneCall({
                          phoneNumber: phone
                        })
                      }} color='#12B3FF' size='44' name='icon-tel'></Iconfont>
                    }
                    <Iconfont handle={() => {
                      // 使用微信内置地图查看位置
                      const { latitude, longitude, address, storeName } = details.store
                      Taro.openLocation({
                        latitude: Number(latitude),
                        longitude: Number(longitude),
                        scale: 18,
                        name: storeName,
                        address
                      })
                    }} color='#12B3FF' size='44' name='icon-zu28'></Iconfont>
                  </View>
                }
              </View>
            ) : (
              <View>
                {<StateList name='服务提供方' context={details.storeName} />}
                {
                  <View className='flex'>
                    <StateList handle={() => {
                      // 使用微信内置地图查看位置
                      const { latitude, longitude, address, storeName } = details.store
                      Taro.openLocation({
                        latitude: Number(latitude),
                        longitude: Number(longitude),
                        scale: 18,
                        name: storeName,
                        address
                      })
                    }}
                      name='门店地址' baseline context={details.store.address} />
                    {
                      details.store.phone && <Iconfont handle={() => {
                        // 使用微信内置拨打电话
                        const { phone } = details.store
                        Taro.makePhoneCall({
                          phoneNumber: phone
                        })
                      }} color='#12B3FF' size='44' name='icon-tel'></Iconfont>
                    }
                    <Iconfont handle={() => {
                      // 使用微信内置地图查看位置
                      const { latitude, longitude, address, storeName } = details.store
                      Taro.openLocation({
                        latitude: Number(latitude),
                        longitude: Number(longitude),
                        scale: 18,
                        name: storeName,
                        address
                      })
                    }} color='#12B3FF' size='44' name='icon-zu28'></Iconfont>
                  </View>
                }

              </View>
            )
          }
          {
            details.apply && details.apply.time > 0 && (
              <View className='order-status-wrap'>
                <View className='order-status'>
                  <View className='text title'>预约信息</View>
                  <View className='row'>
                    <View className='strong'>预约门店：{details.apply.storeName}</View>
                  </View>
                  <View className='row'>
                    <View className='strong'>预约时间：{dayjs.unix(details.apply.time).format('YYYY.MM.DD HH:mm')}</View>
                  </View>
                </View>
              </View>
            )
          }
        </View>
        <View className='margin-top20'>
          <StateList name='订单金额' color='#333' border context={'¥' + details.totalPrice} contextColor='#FF3C31' />
          <StateList name='卡券' context={`-¥${priceMsg.coupon}`} contextColor='#67C23A' />
          <StateList name='红包' context={`-¥${priceMsg.redPacket}`} contextColor='#67C23A' />
          {/* {!details.jihuasuanId ? <StateList name='超级红包' context={`-¥${priceMsg.superRedPacket}`} contextColor='#67C23A' /> : null}
										{!details.jihuasuanId ? <StateList name='保呗红包' context={`-¥${priceMsg.baobeiRedPacketPrice}`} contextColor='#67C23A' /> : null}
										{!details.jihuasuanId ? <StateList name='平台红包' context={`-¥${priceMsg.platformRedPacketPrice}`} contextColor='#67C23A' /> : null} */}
					{
						details.clientSource !== 13 ?  <StateList name='折扣' context={`¥${priceMsg.discountPrice}`} contextColor='#666666' /> : null
					}
          <StateList name='工时费' context={`¥${details.laborFee}`} contextColor='#666666' />
        </View>
        <View className='margin-top20'>
          <StateList name='订单号' context={details.orderNumber} />
          <StateList name='下单时间' context={dayjs.unix(details.createdAt).format('YYYY-MM-DD HH:mm:ss')} />
          {
            details.finishPaymentAt ? <StateList name='支付时间' context={dayjs.unix(details.finishPaymentAt).format('YYYY-MM-DD HH:mm:ss')} /> : null
          }

          {
            details.customerRemark ?
							<View className='margin-top20'>
							<StateList name='订单备注' color='#333'/>
							<View className='remark'>
								{
									details.customerRemark
								}
							</View>
							</View>

						// <StateList name='备注' color='#999999' baseline context={details.customerRemark} />
						: null
          }
        </View>
        {
          fudengLog && fudengLog.length > 0 && <View className='margin-top20 transport' >
            <StateList name='订单进度' color='#333' border contextColor='#FF3C31' />
            <View className='transport-box'>
              <View className='logistics-box'>
                {
                  fudengLog.map((item) => {
                    return <View className='box-item'>
                      <View className='box-item__f'></View>
                      <View className='box-item__dot'></View>
                      <View className='box-item__con'>
                        <View>
                          {item.event == 'ORDER_EVENT_FUDENG_SEND_OUT' ? `${item.eventLabel} ${details.orderFudeng.expectDateLabel}` : item.eventLabel}

                          {
                            item.event == 'ORDER_EVENT_FUDENG_SEND_OUT' && <View className='time'>{details.orderFudeng.expressNumber}</View>
                          }
                          <View className='time'>{dayjs.unix(item.createdAt).format('YYYY-MM-DD HH:mm:ss')}</View>
                        </View>
                        {
                          item.event == 'ORDER_EVENT_FUDENG_SEND_OUT' && <View className="seekTransport" onClick={() => this.seekTransport(details)}>查看物流</View>
                        }
                      </View>
                    </View>
                  })
                }


              </View>

            </View>
          </View>
        }

        {
          details.type !== 5 && details.action && hasAction == false && (
            <View className='bt-handle'>
              {details.action.isCouldViewWarranty === 1 && <View onClick={() => this.viewWarranty(details)} className='btn border'>质保信息</View>}
              {details.action.isCouldViewRefund === 1 && <View onClick={() => this.viewRefund(details)} className='btn border'>查看退款</View>}
              {details.action.isCouldApplyRefund === 1 && <View onClick={() => this.applyRefund(details)} className='btn border'>申请退款</View>}
              {details.action.isCouldComment === 1 && <View onClick={() => this.toEvaluate(details)} className='btn '>评价</View>}
              {details.action.isCouldAfterSale === 1 && <View onClick={() => this.applySale(details)} className='btn border'>申请售后</View>}
              {details.action.isCouldCancel === 1 && <View onClick={() => this.cancelOrder(details)} className='btn border'>取消订单</View>}
              {details.action.isCouldCancelApply === 1 && <View onClick={() => this.cancelApply(details.orderNumber)} className='btn border'>取消预约</View>}
              {details.action.isCouldPay === 1 && <View onClick={() => this.toPay()} className='btn'>去支付</View>}
              {details.action.isCouldUpdateApply === 1 && details.apply && <View onClick={() => this.bookingOrder(details, 'edit')} className='btn'>修改预约</View>}
              {details.action.isCouldApply === 1 && <View onClick={() => this.bookingOrder(details)} className='btn'>去预约</View>}
              {details.isAuthorizing > 0 && <View onClick={() => this.handleConfirmPay(1)} className='btn'>确认信息无误</View>}
            </View>
          )
        }
        {/*
							*/}
      </View>
    )
  }
}
